package com.brayan.webapp.repository.media;

import java.util.LinkedList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.apache.log4j.Logger;

import com.brayan.webapp.model.media.Album;
import com.brayan.webapp.model.media.Album_;

@Stateless
public class AlbumRepository {
	
	private static Logger LOGGER = Logger.getLogger(AlbumRepository.class);

	@PersistenceContext
	EntityManager em;

	public List<Album> findAlbumByString(String album) {
		List<Album> listAlbum = new LinkedList<Album>();

		CriteriaBuilder critBuilder = em.getCriteriaBuilder();
		CriteriaQuery<Album> criteriaQuery = critBuilder.createQuery(Album.class);

		Root<Album> rootAlbum = criteriaQuery.from(Album.class);
		criteriaQuery.orderBy(critBuilder.asc(rootAlbum.get(Album_.name)));
		criteriaQuery.select(rootAlbum).where(critBuilder.like(rootAlbum.get(Album_.name), "%" + album + "%"));

		listAlbum = em.createQuery(criteriaQuery).getResultList();

		return listAlbum;
	}

	/**
	 * Use merge to update or insert.
	 * @param album
	 */
	public void save(Album album) {
		em.merge(album);
	}

	public void delete(long albumId) {
		Album album = em.find(Album.class, albumId);
		if (album != null){
			em.remove(album);
			LOGGER.info("Delete Album with id " + albumId + ".");
		}
	}

	public Album findAlbumById(long albumId) {		
		return em.find(Album.class, albumId);
	}

	public List<Album> getAllAlbums() {
		List<Album> listOfAlbums = new LinkedList<Album>();
		
		CriteriaBuilder critBuilder = em.getCriteriaBuilder();
		CriteriaQuery<Album> criteriaQuery = critBuilder.createQuery(Album.class);

		Root<Album> rootAlbum = criteriaQuery.from(Album.class);
		criteriaQuery.orderBy(critBuilder.asc(rootAlbum.get(Album_.name)));

		listOfAlbums = em.createQuery(criteriaQuery).getResultList();
		return listOfAlbums;
	}
}
